<template>
	<a-timeline>
		<a-timeline-item v-for="node in resultNodeData" :key="node.id" :color="getIconColor(node)">
			<template #dot v-if="node.type === 'startTask' || node.type === 'userTask' || node.type === 'serviceTask'">
				<UserOutlined />
			</template>
			<!--头部标题-->
			<span
				v-if="node.title && node.type !== 'parallelGateway' && node.type !== 'exclusiveGateway'"
				:class="{
					'is-required':
						node.properties.participateInfo[0]?.key === 'CUSTOM' && (!node.userInfo || node.userInfo?.length === 0)
				}"
			>
				{{ node.title }}
			</span>
			<!--并行路由/条件路由-->
			<a-radio-group
				v-if="node.type === 'parallelGateway' || node.type === 'exclusiveGateway'"
				button-style="solid"
				size="small"
				v-model:value="node.checkedValue"
				@change="(evt) => handleRadioChange(node, evt)"
			>
				<a-radio-button v-for="condition in node.conditionNodeList" :key="condition.id" :value="condition.id">
					{{ condition.title }}
				</a-radio-button>
			</a-radio-group>
			<!--人员选择-->
			<div v-if="node.properties?.participateInfo[0]?.key === 'CUSTOM'" class="pt-2">
				<!-- 判断如果是角色，就是角色选择器，以此类推 -->
				<xn-user-selector
					v-if="node.properties.participateInfo[0]?.extJson?.selectType === 'USER'"
					v-model:value="node.userInfo"
					dataType="array"
					:org-tree-api="props.orgTreeApi"
					:user-page-api="props.userPageApi"
					:radioModel="node.properties.participateInfo[0]?.extJson?.selectMode === 'SINGLE'"
					@onBack="(e) => handleChange(node, e)"
				/>
				<xn-role-selector
					v-if="node.properties.participateInfo[0]?.extJson?.selectType === 'ROLE'"
					v-model:value="node.userInfo"
					dataType="array"
					:org-tree-api="props.orgTreeApi"
					:role-page-api="props.rolePageApi"
					:radioModel="node.properties.participateInfo[0]?.extJson?.selectMode === 'SINGLE'"
					@onBack="(e) => handleChange(node, e)"
				/>
				<xn-org-selector
					v-if="node.properties.participateInfo[0]?.extJson?.selectType === 'ORG'"
					v-model:value="node.userInfo"
					dataType="array"
					:org-tree-api="props.orgTreeApi"
					:org-page-api="props.orgPageApi"
					:radioModel="node.properties.participateInfo[0]?.extJson?.selectMode === 'SINGLE'"
					@onBack="(e) => handleChange(node, e)"
				/>
				<xn-position-selector
					v-if="node.properties.participateInfo[0]?.extJson?.selectType === 'POSITION'"
					v-model:value="node.userInfo"
					dataType="array"
					:org-tree-api="props.orgTreeApi"
					:position-page-api="props.positionPageApi"
					:radioModel="node.properties.participateInfo[0]?.extJson?.selectMode === 'SINGLE'"
					@onBack="(e) => handleChange(node, e)"
				/>
			</div>
		</a-timeline-item>
		<a-timeline-item color="#dbdcdc"> 结束 </a-timeline-item>
	</a-timeline>
</template>

<script setup name="LineChart">
	import { cloneDeep } from 'lodash-es'
	import { message } from 'ant-design-vue'
	const rootNodeData = ref([])
	const resultNodeData = ref([]) //页面渲染数据
	const resultNodeDataBk = ref([])
	const selectedNodeId = ref(null)
	const parentIds = ref([])
	// 这些参数，上个界面必传
	const props = defineProps({
		modelDesignData: {
			type: Object,
			default: () => {}
		},
		orgTreeApi: {
			type: Function
		},
		userPageApi: {
			type: Function
		},
		orgPageApi: {
			type: Function
		},
		positionPageApi: {
			type: Function
		},
		rolePageApi: {
			type: Function
		}
	})
	// 初始化数据
	const initData = (rootNode) => {
		rootNode.parentId = null
		rootNodeData.value = rootNode
		// 递归给节点添加parentId
		handleParent(rootNode)
		renderData(rootNode)
		resultNodeData.value = resultNodeDataBk.value
	}
	// 根据id查找节点
	const findNodeById = (node, id) => {
		if (node.id === id) {
			return node
		}
		for (let i = 0; i < (node.conditionNodeList || []).length; i++) {
			const found = findNodeById(node.conditionNodeList[i], id)
			if (found) {
				return found
			}
		}
		if (node.childNode) {
			return findNodeById(node.childNode, id)
		}
		return null
	}
	// 查找所有父节点
	const findParentIds = (node, id, parents = []) => {
		if (node.checkedValue === id) {
			return parents
		}
		if (node.childNode) {
			const result = findParentIds(node.childNode, id, [...parents, node.id])
			if (result) return result
		}
		if (node.conditionNodeList) {
			for (let conditionNode of node.conditionNodeList) {
				const result = findParentIds(conditionNode, id, [...parents, conditionNode.id])
				if (result) return result
			}
		}
		return null
	}
	// 处理change事件
	const handleRadioChange = async (node, evt) => {
		selectedNodeId.value = evt.target.value
		node.checkedValue = evt.target.value
		resultNodeDataBk.value = []
		// 循环找到所有父节点
		parentIds.value = findParentIds(rootNodeData.value, evt.target.value)
		await nextTick()
		renderData(rootNodeData.value)
		resultNodeData.value = resultNodeDataBk.value
	}
	// 扁平化数据渲染
	const renderData = (sourceData) => {
		if (sourceData?.conditionNodeList?.length > 0) {
			let conditionNodeListElement = null
			sourceData.conditionNodeList.forEach((item) => {
				if (parentIds.value?.findIndex((pItem) => pItem === item.id) !== -1 || selectedNodeId.value === item.id) {
					sourceData.checkedValue = item.id
					conditionNodeListElement = item
				}
			})
			if (!conditionNodeListElement) {
				conditionNodeListElement = sourceData.conditionNodeList.find((item) => item.id === sourceData.checkedValue)
			}
			renderData(conditionNodeListElement)
		}
		// 自定义节点
		if (sourceData.properties.participateInfo[0]?.key === 'CUSTOM') {
			const parentNode = resultNodeDataBk.value.find((item) => item.id === sourceData.parentId)
			if (parentNode?.type !== 'exclusiveGateway' && parentNode?.conditionNodeList.length > 0) {
				const node = parentNode?.conditionNodeList?.find((item) => item.id === parentNode.checkedValue)
				const obj = {
					id: node.id + '-custom',
					parentId: node.id,
					title: node.title,
					properties: node.properties,
					type: node.type,
					userInfo: node.properties.participateInfo[0]?.extJson?.customSelectedValue || []
				}
				resultNodeDataBk.value.push(obj)
			}
		}
		// 子节点
		if (sourceData?.childNode && sourceData?.childNode.id) {
			if (sourceData?.childNode?.type !== 'startEvent') {
				resultNodeDataBk.value.push(sourceData.childNode)
			}
			renderData(sourceData.childNode)
		}
	}
	// 给节点添加parentId
	const handleParent = (rootNode) => {
		if (rootNode.childNode && Object.keys(rootNode.childNode).length > 0) {
			rootNode.childNode.parentId = rootNode.id
			if (rootNode.childNode.properties.participateInfo[0]?.key === 'CUSTOM') {
				rootNode.childNode.properties.participateInfo[0].title = rootNode.childNode.title
			}
			handleParent(rootNode.childNode)
		}
		if (rootNode.conditionNodeList) {
			if (rootNode.conditionNodeList[0]) {
				rootNode.checkedValue = rootNode.conditionNodeList[0]?.id
			}
			rootNode.conditionNodeList.forEach((item) => {
				item.parentId = rootNode.id
				handleParent(item)
			})
		}
	}
	const extractCustomNodes = (node, accumulator = []) => {
		if (node.properties.participateInfo[0]?.key === 'CUSTOM') {
			accumulator.push(node)
		}
		if (node?.conditionNodeList?.length > 0) {
			node.conditionNodeList.forEach((item) => {
				extractCustomNodes(item, accumulator)
			})
		}
		// 子节点
		if (node.childNode && Object.keys(node.childNode).length > 0) {
			extractCustomNodes(node.childNode, accumulator)
		}
		return accumulator
	}
	// 	获取自定义节点下人员选择数据
	const getDataInfo = () => {
		let customNodeList = extractCustomNodes(rootNodeData.value).map((node) => {
			const parentNode = findNodeById(rootNodeData.value, node.parentId)
			return {
				id: node.id,
				label: parentNode.type !== 'parallelGateway' ? `${parentNode.title} - ${node.title}` : node.title,
				type: node.properties.participateInfo[0]?.extJson?.selectType,
				value: node.properties.participateInfo[0]?.extJson?.customSelectedValue || []
			}
		})
		// 校验自选条件下是否已选择
		let isValidate = customNodeList.every((node) => node.value && node.value.length > 0)
		if (!isValidate) {
			for (let i = 0; i < customNodeList.length; i++) {
				if (!customNodeList[i].value || customNodeList[i].value.length === 0) {
					message.warning(`【${customNodeList[i].label}】未选择${getTypeName(customNodeList[i].type)}`)
					return false
				}
			}
		} else {
			return customNodeList
		}
	}
	// 获取节点图标颜色
	const getIconColor = (node) => {
		switch (node.type) {
			case 'startTask':
				return 'rgb(87, 106, 149)'
			case 'endTask':
				return '#dbdcdc'
			case 'userTask':
				return 'rgb(255, 148, 62)'
			case 'serviceTask':
				return 'rgb(50, 150, 250)'
			default:
				return 'var(--primary-color)'
		}
	}
	// 获取节点类型名
	const getTypeName = (type) => {
		switch (type) {
			case 'ROLE':
				return '角色'
			case 'ORG':
				return '机构'
			case 'USER':
				return '人员'
			case 'POSITION':
				return '职位'
			default:
				return ''
		}
	}
	// 自定义选择组件数据返回事件
	const handleChange = (node, e) => {
		let nodeData = {}
		if (node.id.indexOf('custom') > -1) {
			nodeData = findNodeById(rootNodeData.value, node.parentId)
		} else {
			nodeData = findNodeById(rootNodeData.value, node.id)
		}
		let { properties: { participateInfo: [firstInfo] = [] } = {} } = nodeData || {}
		firstInfo.extJson.customSelectedValue = e
	}
	// 监听设计器数据变化
	watch(
		props.modelDesignData,
		(newValue) => {
			newValue && initData(cloneDeep(newValue))
		},
		{ deep: true, immediate: true }
	)
	defineExpose({
		getDataInfo
	})
</script>
<style scoped lang="less">
	.is-required {
		position: relative;
		&::before {
			color: #ff4d4f;
			font-size: 14px;
			font-family: SimSun, sans-serif;
			line-height: 1.2;
			content: '*';
			position: absolute;
			left: -10px;
			top: 0;
			width: 10px;
			height: 1px;
		}
	}
</style>
